<template>
  <div class="item2">
    <section class="layer">
      <div class="box">
        <div class="box-header">
          <span class="box-title">查询条件</span>
        </div>
        <div class="box-body">
          <el-form ref="searchForm" :model="searchForm" label-width="60px">
            <el-row :gutter="12">
              <el-col :md="12" :lg="8" :xl="6">
                <el-form-item label="模板名称" prop="tmplName">
                  <el-input v-model="searchForm.tmplName" clearable placeholder="请输入" style="width:100%;" />
                </el-form-item>
              </el-col>
              <el-col :md="12" :lg="8" :xl="6">
                <el-button v-no-more-click type="" @click="resetForm">重置</el-button>
                <el-button v-no-more-click type="primary" @click="search">查询</el-button>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
    </section>
    <section class="layer">
      <div class="box">
        <div class="box-header handle">
          <span class="box-title">模板列表</span>
          <div class="box-tools">
            <el-button v-no-more-click type="success" @click="addNewTem">新增</el-button>
          </div>
        </div>
        <div class="box-body">
          <el-table
            v-loading="table.loading"
            ref="infoTable"
            :data="table.tableData"
            height="tableHeight"
            row-key="signKey"
            fit
            border
            element-loading-spinner="el-loading1"
            highlight-current-row
          >
            <el-table-column type="index" label="序号" width="50" align="center" />
            <el-table-column prop="tmplName" show-overflow-tooltip align="center" label="模板名称" width="310"/>
            <el-table-column prop="tmplUrl" show-overflow-tooltip align="left" label="url">
              <template slot-scope="scope">
                <el-tag
                  v-clipboard:copy="scope.row.tmplUrl"
                  v-clipboard:success="onCopy"
                  v-clipboard:error="onError"
                  class="copy-button"
                  type="success"
                  disable-transitions>复制</el-tag>&nbsp;&nbsp;&nbsp;{{ scope.row.tmplUrl }}
              </template>
            </el-table-column>
            <el-table-column prop="jasperName" show-overflow-tooltip align="left" label="文件名称" width="400">
              <template slot-scope="scope">
                <el-tag
                  v-clipboard:copy="scope.row.jasperName"
                  v-clipboard:success="onCopy"
                  v-clipboard:error="onError"
                  class="copy-button"
                  type="success"
                  disable-transitions>复制</el-tag>&nbsp;&nbsp;&nbsp;{{ scope.row.jasperName }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="160" align="center" fixed="right">
              <template slot-scope="scope">
                <el-button v-no-more-click type="text" class="modify" @click="preview(scope.row)">预览
                </el-button><el-button v-no-more-click type="text" @click="modifyTmpl(scope.row)">修改
                </el-button><el-button v-no-more-click type="text" class="delete" @click="deleteTmpl(scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page="table.pageNum"
            :page-sizes="[15, 30, 50, 100]"
            :page-size="table.pageSize"
            :total="table.total"
            layout="slot, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange">
            <template slot>
              <span class="el-pagination__total">{{ `总共${table.total}条 显示${table.startRow}-${table.endRow}条` }}</span>
            </template>
          </el-pagination>
        </div>
      </div>
    </section>
    <TemplateAdd v-if="addObj.isShow" :data-obj="addObj" @closeAddDialog="closeAddDialog"/>
    <TemplateModify v-if="modifyObj.isShow" :data-obj="modifyObj" @closeModifyDialog="closeModifyDialog"/>
    <!-- 预览参数弹出框 -->
    <el-dialog v-dialogDrag v-if="previewDialogShow.isShow" :title="previewDialogShow.title" :visible.sync="previewDialogShow.isShow" :close-on-click-modal="false" width="50%">
      <el-form ref="form" :model="ruleForm" label-width="120px">
        <el-row v-for="(item, index) in ruleForm.reportParaList" :key="index" :gutter="12">
          <el-col :span="9">
            <el-form-item
              :prop="'reportParaList.' + index + '.paraValue'"
              :rules="{
                required: true, message: '参数不能为空', trigger: 'blur'
              }"
              :label="item.paraName"
            >
              <!-- <el-input :placeholder="item.paraName" v-model="item.paraValue">
                <template slot="">{{ item.paraDesc }}</template>
              </el-input> -->
              <el-input v-model="item.paraValue" placeholder="请输入参数"/>
            </el-form-item>
          </el-col>
          <el-col :span="15" style="line-height:32px;">
            {{ item.paraDesc }}
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewDialogShow.isShow = false">关闭</el-button><el-button type="primary" @click="openPreviewPage">预览</el-button>
      </div>
    </el-dialog>
    <!-- 预览页面 -->
    <el-dialog v-dialogDrag v-if="previewPage.isShow" :title="previewPage.title" :visible.sync="previewPage.isShow" :close-on-click-modal="false" width="100%" class="all-page">
      <section class="layer">
        <div class="box" style="padding-bottom:6px">
          <div class="box-body">
            <el-form ref="prewForm" :model="prewForm" label-width="120px">
              <el-row :gutter="12">
                <el-col :md="12" :lg="8" :xl="6">
                  <el-form-item label="请选择下载类型">
                    <el-select v-model="prewForm.fileType" placeholder="请选择" style="width:100%">
                      <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"/>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :md="12" :lg="16" :xl="18">
                  <el-button v-no-more-click type="primary" style="float: right" @click="$refs.pdf.print()">打印</el-button>
                  <el-button v-no-more-click type="primary" @click="templDownload">下载</el-button>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>
      </section>
      <section
        class="layer"
        style="height: calc(100% - 127px);">
        <div class="box">
          <div class="box-body pdf-box" style="height:100%;overflow:auto;">
            <!-- <div id="previewHtml" v-html="previewHtml"/> -->
            <p style="position:fixed;z-index:1;">
              <!-- 上一页 -->
              <span :class="{grey: currentPage==1}" class="turn" @click="changePdfPage(0)">上一页</span>
              {{ currentPage }} / {{ pageCount }}
              <!-- 下一页 -->
              <span :class="{grey: currentPage==pageCount}" class="turn" @click="changePdfPage(1)">下一页</span>
              <el-button
                :class="{select:idx==0}"
                icon="el-icon-zoom-in"
                type="primary"
                @touchstart="idx=0"
                @touchend="idx=-1"
                @click="scaleD">
                放大
              </el-button>
              <el-button
                :class="{select:idx==1}"
                icon="el-icon-zoom-out"
                type="primary"
                @touchstart="idx=1"
                @touchend="idx=-1"
                @click="scaleX">
                缩小
              </el-button>
            </p>
            <pdf
              v-loading="pdfLoading"
              ref="pdf"
              :page="currentPage"
              :src="src"
              @num-pages="pageCount=$event"
              @page-loaded="currentPage=$event"
              @loaded="loadPdfHandler"
              @error="getpdfError"/>
          </div>
        </div>
      </section>
    </el-dialog>
  </div>
</template>

<script>
import pdf from 'vue-pdf'
import TemplateAdd from './template-add/index'
import TemplateModify from './template-modify/index'
import ApiObj from '@/api/template-management'
export default {
  name: 'PricingSignManagement',
  components: {
    TemplateAdd,
    TemplateModify,
    pdf
  },
  mixins: [

  ],
  props: {
  },
  data() {
    return {
      ruleForm: {
        reportParaList: [
          {
            paraName: ''
          }
        ]
      },
      prewForm: {
        fileType: '1'
      },
      options: [{
        value: '1',
        label: 'pdf'
      },
      {
        value: '2',
        label: 'excel'
      }],
      addObj: {
        isShow: false
      },
      modifyObj: {
        isShow: false,
        row: {}
      },
      previewDialogShow: {
        isShow: false,
        title: '预览-参数设置'
      },
      previewPage: {
        isShow: false,
        title: '预览'
      },
      searchForm: {
        tmplName: ''
      },
      form: {
        tmplName: ''
      },
      rules: {

      },
      menuKey: 1,
      searchInfo: {},
      table: {
        loading: false,
        tableHeight: window.innerHeight - 430,
        tableData: [
        ],
        pageNum: 1,
        pageSize: 15,
        total: 0,
        startRow: 0,
        endRow: 0,
        selectRows: []
      },
      currentPage: 0, // pdf文件页码
      pageCount: 0, // pdf文件总页数
      fileType: 'pdf', // 文件类型
      src: '',
      pdfLoading: true,
      scale: 60, // 放大系数
      idx: -1
    }
  },
  computed: {

  },
  watch: {
  },
  created() {
  },
  mounted() {
    this.getTemplList()
  },
  methods: {
    // 复制成功时的回调函数
    onCopy(e) {
      this.$message({
        type: 'success',
        dangerouslyUseHTMLString: true,
        message: `<strong>操作成功</strong><p>内容已复制到剪切板</p>`,
        duration: 3000
      })
    },
    // 复制失败时的回调函数
    onError(e) {
      this.$alert(`<div class="myalert-header">操作失败</div>
                <div class="myalert-content">抱歉，复制失败</div>`, {
        dangerouslyUseHTMLString: true, confirmButtonText: '确定',
        type: 'error'
      })
    },
    // 下载
    templDownload() {
      let params = {
        ...this.ruleForm,
        fileType: this.prewForm.fileType

      }
      ApiObj.templDownload(params).then(res => {
        let filename = res.headers['content-disposition'].split(';')[1].split('=')[1]
        let url
        if (this.prewForm.fileType === '1') {
          url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/pdf' }))
        } else {
          url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/octet-stream' }))
        }
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', filename)
        document.body.appendChild(link)
        link.click()
      })
    },
    // 删除
    deleteTmpl(row) {
      this.$confirm(`<div class="myalert-header">操作提醒</div><div class="myalert-content">您进行的是删除操作, 是否继续?</div></div>`, {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true,
        cancelButtonText: '取消',
        type: 'warning'
      }).then(_ => {
        ApiObj.templateDelete(row.tmplId).then(res => {
          if (res.data.code === 0) {
            this.$message({
              type: 'success',
              dangerouslyUseHTMLString: true,
              message: `<strong>操作成功</strong><p>${res.data.message}</p>`,
              duration: 3000
            })
            this.getTemplList()
          } else {
            this.$alert(`<div class="myalert-header">操作失败</div>
                <div class="myalert-content">${res.data.message}</div>`, {
              dangerouslyUseHTMLString: true, confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      }).catch(_ => {})
    },
    // 修改模板
    modifyTmpl(row) {
      this.modifyObj.row = row
      this.modifyObj.isShow = true
    },
    // 打开预览页面
    openPreviewPage() {
      let params = this.ruleForm
      ApiObj.previewTmpl(params).then(res => {
        if (res.status === 200) {
          this.$refs.form.validate((valid) => {
            if (valid) {
              let params = this.ruleForm.reportParaList
              this.previewDialogShow.isShow = false
              this.previewPage.isShow = true
              this.src = `${process.env.BASE_API}/report-server/reportTemplateController/print.action?tmplId=${this.ruleForm.reportTemplate.tmplId}`
              for (let item of params) {
                this.src += `&${item.paraName}=${item.paraValue}`
              }
            }
          })
        } else {
          this.$alert(
            `<div class="myalert-header">操作失败</div><div class="myalert-content">${res.data.message}</div></div>`,
            {
              confirmButtonText: '确定',
              dangerouslyUseHTMLString: true,
              type: 'error'
            }
          )
        }
      }).catch(err => {
        this.$alert(
          `<div class="myalert-header">操作失败</div><div class="myalert-content">${err.response.data.message}</div></div>`,
          {
            confirmButtonText: '确定',
            dangerouslyUseHTMLString: true,
            type: 'error'
          }
        )
      })
    },
    // 预览
    preview(row) {
      let params = {
        tmplId: row.tmplId
      }
      ApiObj.templateGetReportTmplDetail(params).then(res => {
        if (res.data.code === 0) {
          this.ruleForm = res.data.data
        }
      })
      this.previewDialogShow.isShow = true
    },
    // 获取模板列表
    getTemplList() {
      this.table.loading = true
      let params = {
        tmplName: '',
        pageSize: this.table.pageSize,
        pageNo: this.table.pageNum,
        ...this.searchForm
      }
      ApiObj.templateGetAllPage(params).then(res => {
        if (res.data.code === 0) {
          this.table.tableData = res.data.data
          this.table.total = res.data.data.length
          const num1 = this.table.pageSize * (this.table.pageNum - 1) + 1
          const num2 = this.table.pageSize * this.table.pageNum > this.table.total ? this.table.total : this.table.pageSize * this.table.pageNum
          this.table.startRow = num1
          this.table.endRow = num2
        }
        this.table.loading = false
      })
    },
    addNewTem() {
      this.addObj.isShow = true
    },
    // 充值查询条件
    resetForm() {
      this.$refs.searchForm.resetFields()
      this.search()
    },
    // 搜索
    search() {
      this.table.pageSize = 15
      this.table.pageNum = 1
      this.getTemplList()
    },
    // 关闭新增弹出框
    closeAddDialog() {
      this.addObj.isShow = false
      this.getTemplList()
    },
    // 关闭修改弹窗
    closeModifyDialog() {
      this.modifyObj.isShow = false
      this.getTemplList()
    },
    // 分页Size
    handleSizeChange(size) {
      this.table.pageSize = size
      this.getTemplList()
    },
    // 分页选择
    handleCurrentChange(currentPage) {
      this.table.pageNum = currentPage
      this.getTemplList()
    },
    // 改变PDF页码,val传过来区分上一页下一页的值,0上一页,1下一页
    changePdfPage(val) {
      if (val === 0 && this.currentPage > 1) {
        this.currentPage--
      }
      if (val === 1 && this.currentPage < this.pageCount) {
        this.currentPage++
      }
    },
    // pdf加载时
    loadPdfHandler(e) {
      this.currentPage = 1 // 加载的时候先加载第一页
      this.pdfLoading = false
      this.$refs.pdf.$el.style.width = parseInt(this.scale) + '%'
    },
    // 放大
    scaleD() {
      this.scale += 5
      this.$refs.pdf.$el.style.width = parseInt(this.scale) + '%'
    },
    // 缩小
    scaleX() {
      this.scale += -5
      this.$refs.pdf.$el.style.width = parseInt(this.scale) + '%'
    },
    // 获取pdf时异常
    getpdfError(e) {
      if (e.status === 500) {
        this.$alert(
          `<div class="myalert-header">操作失败</div><div class="myalert-content">报表生成异常</div></div>`,
          {
            confirmButtonText: '确定',
            dangerouslyUseHTMLString: true,
            type: 'error'
          }
        )
      }
    }
  }
}
</script>

<style scoped lang="scss">
.pdf-box{
  &>span{
    margin:0 auto;
  }
}
.copy-button{
  cursor: pointer;
}
.all-page{

  height: 100%!important;
  .el-form .el-form-item{
    margin-bottom:0px;
  }
  /deep/.el-dialog{
    height: 100%!important;
  }
   /deep/ .el-dialog__body{
   max-height: 100%;
 }
 #previewHtml{
  height: 100%;
   overflow-y: auto;
 }
 .turn{
  cursor:pointer;
 }
}
</style>
